package liuds.music;

import android.app.Application;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import liuds.music.adapter.MusicAdapter;
import liuds.music.adapter.SearchAdapter;
import liuds.music.adapter.SearchHistoryAdapter;
import liuds.music.model.DbHelp;
import liuds.music.model.Music;
import liuds.music.utils.Http;
import liuds.music.utils.MusicUtils;
import liuds.music.utils.Utils;

/**
 * Created by Administrator on 2018/5/3.
 */

public class SearchActivity extends BaseActivity implements SearchHistoryAdapter.OnSearchHistoryItemClickListener{

    private ListView searchListView;
    private SearchAdapter searchAdapter;
    private List<Music> searchMusicList = new ArrayList<>();

    private SearchHandler searchHandler;

    private LinearLayout history;
    private SearchHistoryAdapter searchHistoryAdapter;

//    private SearchView.SearchAutoComplete searchEt;
    private EditText searchEt;

    private List<Map<String,Object>> historys;

    private DbHelp dbHelp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        initSearchView();

        dbHelp = DbHelp.getInstance();
        historys = dbHelp.getSearchHistory();

        getSupportActionBar().setDisplayShowTitleEnabled(false);
        searchHandler = new SearchHandler();

        history = findViewById(R.id.history);
        if(historys.size()>0){
            history.setVisibility(View.VISIBLE);
        }
        ImageButton clearHistoryBtn = findViewById(R.id.clear);
        clearHistoryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelp.clearSearchHistory();
                historys.clear();
                searchHistoryAdapter.notifyDataSetChanged();
                history.setVisibility(View.GONE);
            }
        });

        RecyclerView historyView = findViewById(R.id.historyView);
        GridLayoutManager layoutManager = new GridLayoutManager(SearchActivity.this,2,GridLayoutManager.VERTICAL,false);
        historyView.setLayoutManager(layoutManager);
        DividerItemDecoration divider = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this,R.drawable.item_divider));
        historyView.addItemDecoration(divider);

        searchHistoryAdapter = new SearchHistoryAdapter(SearchActivity.this,historys);
        searchHistoryAdapter.setOnSearchHistoryItemClickListener(this);
        historyView.setAdapter(searchHistoryAdapter);
    }

    private final int SEARCH_TAG = 1;
    private void initSearchView() {
        View searchView = LayoutInflater.from(this).inflate(R.layout.search_view,toolbar);

        final ImageButton clearSearch = searchView.findViewById(R.id.clearSearch);

        searchEt = searchView.findViewById(R.id.searchEt);
        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Utils.toast(v.getText().toString());
//                Http.get("/user/userInfo", new Http.OnSuccessListener() {
//                    @Override
//                    public void onSuccess(Object result) {
//
//                    }
//                },null,null);
                return true;
            }
        });
        searchEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus && !searchEt.getText().toString().equals("")){
                    searchMusicList.clear();
                    searchMusicList.addAll(findMusicByName(searchEt.getText().toString()));
                    searchAdapter.notifyDataSetChanged();
                }
            }
        }
        );
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                clearSearch.setVisibility(s.length()>0?View.VISIBLE:View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(searchHandler.hasMessages(SEARCH_TAG)){
                    searchHandler.removeMessages(SEARCH_TAG);
                }
                if(s.toString().equals("")){
                    searchMusicList.clear();
                    searchAdapter.notifyDataSetChanged();
                }else{
                    Message msg = new Message();
                    msg.what = SEARCH_TAG;
                    msg.obj = s;
                    searchHandler.sendMessageDelayed(msg,300);
                }
            }
        });

        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEt.setText("");
            }
        });

        initSearchWindow();
    }


    private void initSearchWindow() {
        searchListView = findViewById(R.id.searchListView);

        searchAdapter = new SearchAdapter(this,searchMusicList);
        searchListView.setAdapter(searchAdapter);

        searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Music music = searchAdapter.getItem(position);
                dbHelp.addSearchHistory(music.getTitle());
                int index = MusicUtils.getPlayMusicList().indexOf(music);
                Intent intent =getIntent();
                Bundle bundle =new Bundle();
                bundle.putInt("index",index);//回发的消息
                intent.putExtras(bundle);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
    }


    private class SearchHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SEARCH_TAG:
                    searchMusicList.clear();
                    searchMusicList.addAll(findMusicByName(msg.obj+""));
                    searchAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    private List<Music> findMusicByName(String name) {
        List<Music> searchMusicList = new ArrayList<>();
        for(Music music : MusicUtils.getPlayMusicList()){
            if(music.getTitle().toLowerCase().contains(name.toLowerCase())){
                searchMusicList.add(music);
                if(searchMusicList.size()>=10)break;
            }
        }
        return searchMusicList;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                if(!Utils.inRangeOfView(searchListView,ev)){
                    searchMusicList.clear();
                    searchAdapter.notifyDataSetChanged();
                }
                break;
        }

        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onSearchHistoryItemClick(View v) {
        TextView title = v.findViewById(R.id.title);
        searchEt.setText(title.getText().toString());
    }

    @Override
    public void onSearchHistoryItemMenuClick(int position) {
        dbHelp.delSearchHistory(Integer.parseInt(historys.get(position).get("_id")+""));
        historys.remove(position);
        searchHistoryAdapter.notifyDataSetChanged();
        if(historys.size()==0){
            history.setVisibility(View.GONE);
        }
    }

}
